<template>
  <div class="login-page">
    <div class="login-container">
      <!-- Logo区域 -->
      <div class="logo-section">
        <div class="logo">
          <van-image
            src="./images/NY_RectangularFavicon.png"
            width="80"
            height="80"
          />
        </div>
        <h1 class="app-title">校园新闻网</h1>
        <p class="app-subtitle">欢迎登录</p>
      </div>

      <!-- 登录表单 -->
      <van-form @submit="handleLogin">
        <van-cell-group inset>
          <van-field
            v-model="loginForm.username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
            left-icon="user-o"
          />
          <van-field
            v-model="loginForm.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
            left-icon="lock"
          />
        </van-cell-group>

        <!-- 登录选项 -->
        <div class="login-options">
          <van-checkbox v-model="rememberMe">记住密码</van-checkbox>
          <span class="forgot-password" @click="handleForgotPassword">忘记密码？</span>
        </div>

        <!-- 登录按钮 -->
        <div class="login-button">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            loading-text="登录中..."
          >
            登录
          </van-button>
        </div>
      </van-form>

      <!-- 其他登录方式 -->
      <div class="other-login">
        <div class="divider">
          <span>其他登录方式</span>
        </div>
        <div class="social-login">
          <van-button
            icon="wechat"
            type="success"
            round
            @click="handleWechatLogin"
          >
            微信登录
          </van-button>
        </div>
      </div>

      <!-- 注册链接 -->
      <div class="register-link">
        <span>还没有账号？</span>
        <span class="link" @click="handleRegister">立即注册</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Form, Field, CellGroup, Button, Checkbox, Image, showToast, showSuccessToast, showFailToast } from 'vant'
import { userApi } from '../utils/api'
import { useUserStore } from '../stores/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const loginForm = ref({
  username: '',
  password: ''
})

const rememberMe = ref(false)
const loading = ref(false)

// 检查登录状态
const checkLoginStatus = async () => {
  try {
    const isLoggedIn = await userStore.checkLoginStatus(userApi.getPermission)
    if (isLoggedIn) {
      // 已登录，跳转到首页或返回页面
      const redirectPath = route.query.redirect || '/'
      router.replace(redirectPath)
      return true
    }
  } catch (error) {
    console.error('检查登录状态失败:', error)
  }
  return false
}

// 处理登录
const handleLogin = async (values) => {
  try {
    loading.value = true

    // 使用Pinia store处理登录
    const result = await userStore.login({
      username: values.username,
      password: values.password
    }, userApi.login)

    if (result.success) {
      if (rememberMe.value) {
        localStorage.setItem('rememberedUser', values.username)
      }

      showSuccessToast('登录成功')

      // 跳转到指定页面或首页
      setTimeout(() => {
        const redirectPath = route.query.redirect || '/'
        router.replace(redirectPath)
      }, 1000)
    } else {
      showFailToast(result.message || '用户名或密码错误')
    }
  } catch (error) {
    console.error('登录失败:', error)
    showFailToast('登录失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 处理忘记密码
const handleForgotPassword = () => {
  showToast('请联系管理员重置密码')
}

// 处理微信登录
const handleWechatLogin = () => {
  showToast('微信登录功能暂未开放')
}

// 处理注册
const handleRegister = () => {
  showToast('请联系辅导员或教务处注册')
}

// 页面加载时检查登录状态和记住的用户名
onMounted(async () => {
  // 检查是否已登录
  await checkLoginStatus()

  // 恢复记住的用户名
  const rememberedUser = localStorage.getItem('rememberedUser')
  if (rememberedUser) {
    loginForm.value.username = rememberedUser
    rememberMe.value = true
  }
})
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 400px;
}

.logo-section {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  margin-bottom: 16px;
}

.app-title {
  font-size: 24px;
  font-weight: 600;
  color: #000000; 
  margin: 0 0 8px 0;
}

.app-subtitle {
  font-size: 14px;
  color: #969799;
  margin: 0;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
}

.forgot-password {
  color: #ff6b00; 
  font-size: 14px;
  cursor: pointer;
}

.login-button {
  padding: 20px 16px 10px;
}

.login-button .van-button {
  background-color: #08a7eb;
  border-color: #03a9f1;
}

.other-login {
  margin: 20px 0;
}

.divider {
  text-align: center;
  position: relative;
  margin: 20px 0;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #ebedf0;
}

.divider span {
  background: white;
  color: #969799;
  padding: 0 16px;
  font-size: 14px;
  position: relative;
}

.social-login {
  text-align: center;
}

.register-link {
  text-align: center;
  color: #969799;
  font-size: 14px;
}

.link {
  color: #ff6b00; 
  cursor: pointer;
  margin-left: 4px;
}

/* 自定义表单样式 */
:deep(.van-cell-group--inset) {
  margin: 0 16px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #ebedf0;
}

:deep(.van-field__left-icon) {
  color: #ff6b00; 
}

:deep(.van-field__control::placeholder) {
  color: #c8c9cc;
}
</style>
